
package org.search.ui;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import org.lobobrowser.html.HtmlRendererContext;
import org.lobobrowser.html.gui.HtmlPanel;
import org.lobobrowser.html.parser.DocumentBuilderImpl;
import org.lobobrowser.html.test.SimpleHtmlRendererContext;
import org.serch.action.SearchAction;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class SearchDialog extends JFrame {

    private JLabel label;
    private JTextField text;
    private JButton okButton;
    private HtmlPanel htmlPanel;

    private void createControls() {
        
        setSize(600, 200);
        
        setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        setLayout(new GridBagLayout());
        c = new GridBagConstraints();
        c.insets = new Insets(2, 2, 2, 2);
//        c.weighty = 1.0;
//        c.weightx = 1.0;
        c.gridx = 0;
        c.gridy = 0;
        label = new JLabel("Enter Query");
        add(label);
        c.gridx = 0;
        c.gridy = 0;
        
        text = new JTextField(100);
        add(text);
        c.gridx = 0;
        c.gridy = 1;
        okButton = new JButton("Ok");
        add(okButton);
        c.gridx = 1;
        htmlPanel = new HtmlPanel();
        add(htmlPanel);
        addListeners();
    }

    final String[] searchResult = new String[1];

    private void addListeners() {

        okButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                searchResult[0] = SearchAction.sendOutput(text.getText());
                renderResult();
            }
        });

    }

    private void renderResult() {
        try {
            HtmlRendererContext rcontext = new SimpleHtmlRendererContext(htmlPanel);
            Document doc = new DocumentBuilderImpl(rcontext)
                .parse(new ByteArrayInputStream(searchResult[0].getBytes()));

            htmlPanel.setDocument(doc, rcontext);
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public SearchDialog() {
        super();
        createControls();
    }

}
